package com.ruoyi.business.service.impl;

import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.business.domain.CategoryTree;
import com.ruoyi.business.domain.ProductSku;
import com.ruoyi.business.domain.TProductCategory;
import com.ruoyi.business.mapper.CategoryTreeMapper;
import com.ruoyi.business.mapper.ProductSkuMapper;
import com.ruoyi.business.mapper.TProductCategoryMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.ProductSpuMapper;
import com.ruoyi.business.domain.ProductSpu;
import com.ruoyi.business.service.IProductSpuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 商品SPUService业务层处理
 *
 * @author ruoyi
 * @date 2025-03-15
 */
@Service
public class ProductSpuServiceImpl implements IProductSpuService
{
    @Autowired
    private ProductSpuMapper productSpuMapper;

    @Autowired
    private TProductCategoryMapper tProductCategoryMapper;

    @Autowired
    private CategoryTreeMapper categoryTreeMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;
    /**
     * 查询商品SPU
     *
     * @param id 商品SPU主键
     * @return 商品SPU
     */
    @Override
    public ProductSpu selectProductSpuById(Long id)
    {
        return productSpuMapper.selectProductSpuById(id);
    }

    /**
     * 查询商品SPU列表
     *
     * @param productSpu 商品SPU
     * @return 商品SPU
     */
    @Override
    public List<ProductSpu> selectProductSpuList(ProductSpu productSpu) {
        // 1️⃣ 先分页查询 SPU
        List<ProductSpu> spuList = productSpuMapper.selectProductSpuList(productSpu);
        if (spuList.isEmpty()) {
            return spuList;
        }

        // 2️⃣ 获取所有 SPU 的 ID
        List<Long> spuIds = spuList.stream().map(ProductSpu::getId).collect(Collectors.toList());

        // 3️⃣ 批量查询 SKU
        List<ProductSku> skuList = productSkuMapper.selectSkuBySpuIds(spuIds);

        // 4️⃣ 按 `SPU ID` 进行分组
        Map<Long, List<ProductSku>> spuSkuMap = skuList.stream().collect(Collectors.groupingBy(ProductSku::getProductSpu));

        // 5️⃣ 将 SKU 绑定到 SPU 上
        for (ProductSpu spu : spuList) {
            spu.setProductSkus(spuSkuMap.getOrDefault(spu.getId(), new ArrayList<>()));
        }

        return spuList;
    }

    /**
     * 新增商品SPU
     *
     * @param productSpu 商品SPU
     * @return 结果
     */
    @Override
    public int insertProductSpu(ProductSpu productSpu)
    {
        handerProductSpu(productSpu);
        productSpuMapper.insertProductSpu(productSpu);
        return addProductSku(productSpu);
    }

    /**
     * 添加sku货品
     * @param productSpu
     */
    private int addProductSku(ProductSpu productSpu) {
        System.out.println(productSpu.getId());
        List<ProductSku> productSkus = productSpu.getProductSkus();
        productSkus.forEach(sku -> {
            sku.setSkuCode(generateSPUCode());
            sku.setProductSpu(productSpu.getId());
        });
        return productSkuMapper.insertProductSkus(productSkus);
    }

    private void handerProductSpu(ProductSpu productSpu) {
        productSpu.setCreateTime(DateUtils.getNowDate());
        productSpu.setSpuCode(generateSPUCode()); // 生成SPU编码
        productSpu.setIsStandard("1".equals(productSpu.getIsStandard()) ? "标品" : "非标品"); // 设置商品类型

        // 处理分类信息
        List<Long> categoryIds = productSpu.getCategoryIds();
        productSpu.setCategoryId(categoryIds.stream().map(String::valueOf).collect(Collectors.joining(",")));

        List<TProductCategory> categories = tProductCategoryMapper.selectTProductCategoryByIds(categoryIds);
        if (!categories.isEmpty()) {
            productSpu.setProductCategoryLevel1Name(categories.get(0).getCategoryName());
            if (categories.size() > 1) productSpu.setProductCategoryLevel2Name(categories.get(1).getCategoryName());
            if (categories.size() > 2) productSpu.setProductCategoryLevel3Name(categories.get(2).getCategoryName());
        }

        // 处理美团渠道信息
        List<Long> meituanChannelIds = Optional.ofNullable(productSpu.getMeituanAttr()).orElse(Collections.emptyList());
        productSpu.setMeituanChannelId(meituanChannelIds.stream().map(String::valueOf).collect(Collectors.joining(",")));

        List<CategoryTree> categoryTrees = categoryTreeMapper.selectCategoryTreeByIds(meituanChannelIds);
        if (!categoryTrees.isEmpty()) {
            productSpu.setMeituanChannelLevel1(categoryTrees.get(0).getName());
            if (categoryTrees.size() > 1) productSpu.setMeituanChannelLevel2(categoryTrees.get(1).getName());
            if (categoryTrees.size() > 2) productSpu.setMeituanChannelLevel3(categoryTrees.get(2).getName());
        }

        List<ProductSku> productSkus = productSpu.getProductSkus();
        productSkus.stream().forEach(e-> System.out.println(e));
     }


    public static String generateSPUCode() {
        // 获取当前时间，精确到毫秒
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));

        // 生成 3 位随机数
        Random random = new Random();
        int randomSuffix = 100 + random.nextInt(900); // 确保是 3 位数

        // 组合成 SPU 编码
        return timestamp + randomSuffix;
    }

    /**
     * 修改商品SPU
     *
     * @param productSpu 商品SPU
     * @return 结果
     */
    @Override
    public int updateProductSpu(ProductSpu productSpu)
    {
        productSpu.setUpdateTime(DateUtils.getNowDate());
        productSpu.setIsStandard("1".equals(productSpu.getIsStandard()) ? "标品" : "非标品"); // 设置商品类型

        // 处理分类信息
        List<Long> categoryIds = productSpu.getCategoryIds();
        productSpu.setCategoryId(categoryIds.stream().map(String::valueOf).collect(Collectors.joining(",")));

        List<TProductCategory> categories = tProductCategoryMapper.selectTProductCategoryByIds(categoryIds);
        if (!categories.isEmpty()) {
            productSpu.setProductCategoryLevel1Name(categories.get(0).getCategoryName());
            if (categories.size() > 1) productSpu.setProductCategoryLevel2Name(categories.get(1).getCategoryName());
            if (categories.size() > 2) productSpu.setProductCategoryLevel3Name(categories.get(2).getCategoryName());
        }

        // 处理美团渠道信息
        List<Long> meituanChannelIds = Optional.ofNullable(productSpu.getMeituanAttr()).orElse(Collections.emptyList());
        productSpu.setMeituanChannelId(meituanChannelIds.stream().map(String::valueOf).collect(Collectors.joining(",")));

        List<CategoryTree> categoryTrees = categoryTreeMapper.selectCategoryTreeByIds(meituanChannelIds);
        if (!categoryTrees.isEmpty()) {
            productSpu.setMeituanChannelLevel1(categoryTrees.get(0).getName());
            if (categoryTrees.size() > 1) productSpu.setMeituanChannelLevel2(categoryTrees.get(1).getName());
            if (categoryTrees.size() > 2) productSpu.setMeituanChannelLevel3(categoryTrees.get(2).getName());
        }


        // **重新插入新的 SKU**
        List<ProductSku> newSkus = productSpu.getProductSkus();
        if (newSkus != null && !newSkus.isEmpty()) {
            // **更新 SPU**
            productSpuMapper.updateProductSpu(productSpu);
            // **删除旧的 SKU**
            productSkuMapper.deleteProductSkusBySpuId(productSpu.getId());

            // **遍历 SKU，补充缺失的 skuCode**
            for (ProductSku sku : newSkus) {
                sku.setProductSpu(productSpu.getId()); // 绑定 SPU ID
                if (sku.getSkuCode() == null || sku.getSkuCode().trim().isEmpty()) {
                    sku.setSkuCode(generateSPUCode()); // 生成 skuCode
                }
            }
            newSkus.forEach(sku -> sku.setProductSpu(productSpu.getId())); // 绑定 SPU ID

                productSkuMapper.insertProductSkus(newSkus);
        }
        return 1;
    }

    /**
     * 批量删除商品SPU
     *
     * @param ids 需要删除的商品SPU主键
     * @return 结果
     */
    @Override
    public int deleteProductSpuByIds(Long[] ids)
    {
        return productSpuMapper.deleteProductSpuByIds(ids);
    }

    /**
     * 删除商品SPU信息
     *
     * @param id 商品SPU主键
     * @return 结果
     */
    @Override
    public int deleteProductSpuById(Long id)
    {
        return productSpuMapper.deleteProductSpuById(id);
    }


    /**
     * 导入文件批量插入
     * @param productSpuList
     * @return
     */
    @Override
    public int batchInsertProductSpu(List<ProductSpu> productSpuList) {
        return productSpuMapper.insertBatchProductSpu(productSpuList);
    }
    @Override
    @Transactional
    public void importData(MultipartFile file) {
        try (InputStream is = file.getInputStream()) {
            Workbook workbook = new XSSFWorkbook(is);
            Sheet sheet = workbook.getSheetAt(0);

            // 存放 SPU 和 SKU 的集合
            List<ProductSpu> productSpuList = new ArrayList<>();
            List<ProductSku> productSkuList = new ArrayList<>();
            Map<String, ProductSpu> spuMap = new HashMap<>();
            // 解析 Excel 数据
            for (Row row : sheet) {
                if (row.getRowNum() == 0) continue; // 跳过表头

                String spuCode = getCellValue(row, 0);
                ProductSpu productSpu = spuMap.get(spuCode);  // 根据 spuCode 查找是否已经存在该 SPU

                // 如果 SPU 不存在，则创建新的 SPU
                if (productSpu == null) {
                    productSpu = new ProductSpu();
                    productSpu.setSpuCode(spuCode);
                    productSpu.setName(getCellValue(row, 1));
                    productSpu.setProductCategoryLevel1Name(getCellValue(row, 2));
                    productSpu.setProductCategoryLevel2Name(getCellValue(row, 3));
                    productSpu.setProductCategoryLevel3Name(getCellValue(row, 4));
                    productSpu.setBrand(getCellValue(row, 5));
                    productSpu.setIsStandard(getCellValue(row, 6));
                    productSpu.setOrigin(getCellValue(row, 7));
                    productSpu.setSellingPoints(getCellValue(row, 20));
                    productSpu.setDescription(getCellValue(row, 21));

                    // 添加美团类目
                    productSpu.setMeituanChannelLevel1(getCellValue(row, 23));
                    productSpu.setMeituanChannelLevel2(getCellValue(row, 24));
                    productSpu.setMeituanChannelLevel3(getCellValue(row, 25));

                    productSpuList.add(productSpu);
                    spuMap.put(spuCode, productSpu);  // 存储带有 id 的 SPU
                }

                // 读取 SKU 信息并关联到对应的 SPU
                ProductSku productSku = new ProductSku();
                productSku.setSpuCode(spuCode);
                productSku.setSkuCode(getCellValue(row, 9));
                productSku.setSpecification(getCellValue(row, 10));
                productSku.setWeight(getNumericCellValue(row, 11));
                productSku.setWeightUnit(getCellValue(row, 12));
                productSku.setSalesUnit(getCellValue(row, 13));
                productSku.setBarcode(getCellValue(row, 14));
                productSku.setInputTaxRate(getNumericCellValue(row, 15));
                productSku.setOutputTaxRate(getNumericCellValue(row, 16));
                productSku.setMinPurchaseQuantity(getLongCellValue(row, 17));
                productSku.setExternalCode(getCellValue(row, 18));
                productSku.setProductAttributes(getCellValue(row, 19));
                productSku.setHeadquartersRetailPrice(getNumericCellValue(row, 22));
                // 将 SKU 添加到列表
                productSkuList.add(productSku);
            }
            // 批量插入 SPU 和 SKU
            if (!productSpuList.isEmpty()) {
                // 1️⃣ 批量插入 SPU，并获取 ID
                productSpuMapper.insertBatchProductSpu(productSpuList);
                // 2️⃣ 遍历 productSpuList，确保 spuMap 存储的是带有 ID 的 SPU
                for (ProductSpu spu : productSpuList) {
                    spuMap.put(spu.getSpuCode(), spu);  // 更新 spuMap，使其包含数据库分配的 ID
                }
                // 3️⃣ 绑定 SPU ID 到 SKU
                for (ProductSku sku : productSkuList) {
                    ProductSpu spu = spuMap.get(sku.getSpuCode());
                    if (spu != null) {
                        sku.setProductSpu(spu.getId());  // 绑定正确的 SPU ID
                        sku.setSpuCode(spu.getSpuCode());  // 绑定正确的 SPU 编码
                    }
                }
                // 4️⃣ 批量插入 SKU
                if (!productSkuList.isEmpty()) {
                    productSkuMapper.insertProductSkus(productSkuList);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("数据导入失败：" + e.getMessage(), e);
        }
    }


    /**
     * 获取 Excel 单元格的字符串值，避免 NullPointerException
     */
    private String getCellValue(Row row, int index) {
        Cell cell = row.getCell(index);
        if (cell == null) {
            return "";
        }
        // 处理不同类型的单元格
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }

    /**
     * 获取 Excel 单元格的数值（BigDecimal），避免 NullPointerException
     */
    private BigDecimal getNumericCellValue(Row row, int index) {
        Cell cell = row.getCell(index);
        if (cell == null || cell.getCellType() != CellType.NUMERIC) {
            return BigDecimal.ZERO;
        }
        return BigDecimal.valueOf(cell.getNumericCellValue());
    }

    /**
     * 获取 Excel 单元格的整数值（Long），避免 NullPointerException
     */
    private Long getLongCellValue(Row row, int index) {
        Cell cell = row.getCell(index);
        if (cell == null || cell.getCellType() != CellType.NUMERIC) {
            return 0L;
        }
        return (long) cell.getNumericCellValue();
    }



}
